package org.fxd.zweixin.busi_system.file.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.fxd.zweixin.busi_system.file.domain.t_fk_file;
import org.fxd.zweixin.util.DateTools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.utils.ChkTools;
import org.tmsps.ne4spring.utils.FileTools;
import org.tmsps.ne4spring.utils.JsonUtil;
import org.tmsps.ne4spring.utils.img.ImgBase64Tools;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "文件上传")
@Controller
@Scope("prototype")
public class UploadAction extends BaseAction {

	@Value("${backletter.filepath}")
	private String DATA_PATH;

	
	private t_fk_file save_file(MultipartFile upfile, String open_download, String suff, String file_name)
			throws Exception {
		String suffix = null;
		if (ChkTools.isNotNull(suff)) {
			suffix = suff;
		} else {
			suffix = FileTools.getSuffix(upfile.getOriginalFilename());
		}
		String new_file_name = System.currentTimeMillis() + "." + suffix;
		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;
		// 保存文件
		t_fk_file tf = new t_fk_file();
		if (ChkTools.isNotNull(file_name)) {
			if (file_name.lastIndexOf("\\") != -1) {
				file_name = file_name.substring(file_name.lastIndexOf("\\") + 1);
			}
			tf.setFile_name(file_name);
		} else {
			String originalFilename = upfile.getOriginalFilename();
			if (originalFilename.lastIndexOf("\\") != -1) {
				originalFilename = originalFilename.substring(originalFilename.lastIndexOf("\\") + 1);
			}
			if (ChkTools.isNotNull(suff)) {
				tf.setFile_name(originalFilename.substring(0, originalFilename.lastIndexOf(".")) + "." + suff);
			} else {
				tf.setFile_name(originalFilename);
			}
		}
		tf.setNew_file_name(new_file_name);
		tf.setFolder(folder);
		tf.setOpen_download(open_download);
		tf.setFolder_url(folder_url);
		tf.setContent_type(upfile.getContentType());
		tf.setSize(upfile.getSize());
		// 获取保存路径
		File newFile = new File(DATA_PATH + File.separator + folder + File.separator + tf.getNew_file_name());
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		upfile.transferTo(newFile);
		bs.saveObj(tf);
		return tf;
	}

	@ApiOperation(value = "获取上传文件列表")
	@PostMapping("/upload")
	private void upload(@RequestParam MultipartFile file, HttpServletRequest req, HttpServletResponse resp,
			String open_download, String suff, String file_name) throws Exception {
		resp.setCharacterEncoding("utf-8");
		logger.info(file.getName());
		t_fk_file tf = save_file(file, open_download, suff, file_name);
		Map<String, Object> end = new HashMap<String, Object>();
		// 发送保存结果
		end.put("file_id", String.valueOf(tf.getKid()));
		end.put("name", tf.getFile_name());
		end.put("content_type", tf.getContent_type());
		resp.getWriter().print(JsonUtil.toJson(end));
		resp.getWriter().flush();
	}

	
	@ApiOperation(value = "上传文件", notes = "上传文件，base64格式", httpMethod = "POST")
	@PostMapping("/upload_base64")
	public void upload_base64(String img, HttpServletRequest req, HttpServletResponse resp)
			throws IllegalStateException, IOException {
		resp.setCharacterEncoding("utf-8");

		String suffix = "png";
		String filename = System.currentTimeMillis() + "." + suffix;
		int year = DateTools.getYear();
		int month = DateTools.getMonth();
		String folder = year + File.separator + month;
		String folder_url = year + "/" + month;
		// 保存文件
		t_fk_file tf = new t_fk_file();
		tf.setFile_name(filename);
		tf.setNew_file_name(filename);
		tf.setFolder(folder);
		tf.setOpen_download("是");
		tf.setFolder_url(folder_url);
		tf.setContent_type("image/png");
		// 获取保存路径
		File newFile = new File(DATA_PATH + File.separator + folder + File.separator + tf.getNew_file_name());
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}
		ImgBase64Tools.generateImage(img, newFile.getAbsolutePath());
		tf.setSize(newFile.length());
		bs.saveObj(tf);
		Map<String, Object> end = new HashMap<String, Object>();
		// 发送保存结果
		end.put("file_id", tf.getKid());
		end.put("file_name", tf.getFile_name());
		end.put("content_type", tf.getContent_type());
		resp.getWriter().print(JsonUtil.toJson(end));
		resp.getWriter().flush();
	}

}
